<template>
  <div class="shipment-order-edit-wrapper app-container">
    <div class="shipment-order-content">
      <el-form label-width="108px" :model="form" ref="form" :rules="rules">
        <!-- <el-form-item :label="$t('outBound.OrderNo')" prop="shipmentOrderNo">
          <el-input class="w200" v-model="form.shipmentOrderNo" placeholder="出库单号" disabled="disabled"></el-input>
        </el-form-item> -->
        <el-form-item :label="$t('outBound.type')" prop="shipmentOrderType">
          {{ $t('outBound.E-commerce outbound') }}
          <!-- <el-radio-group v-model="form.shipmentOrderType">
            <el-radio-button v-for="dict in dict.type.wms_shipment_type" :key="dict.value"
                             :label="dict.value">{{ dict.label }}
            </el-radio-button>
          </el-radio-group> -->
        </el-form-item>
        <el-form-item v-if="YT_roles" :label="$t('common.selectCustomer')"  prop="customerId">
          <WmsCustomerSelect v-model="form.customerId"></WmsCustomerSelect>
        </el-form-item>
        <el-form-item :label="$t('common.selectWare')" prop="warehouseId">
          <WmsAreaCascader v-model="form.warehouseId" size="small"></WmsAreaCascader>
        </el-form-item>
        <!-- <el-form-item :label="$t('fiance.amount')" prop="receivableAmount" v-show="hasCustomer">
          <el-input-number v-model="form.receivableAmount" :precision="2" :min="0" :label="$t('common.pleaseInput')"></el-input-number>
        </el-form-item> -->
        <el-form-item :label="$t('common.container')" prop="rackId">
          <el-select v-model="form.rackId" :placeholder="$t('common.container')" @focus="getContainerId">
            <el-option v-for="item in ContainerOptions" :key="item.id" :label="item.rackName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.orderNo')" prop="orderNo">
          <el-input v-model="form.orderNo" :placeholder="$t('common.pleaseInput')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('outBound.address')" prop="orderAddress">
          <el-input v-model="form.orderAddress" :placeholder="$t('common.pleaseInput')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('order.paymentMethod')" prop="paymentMethod">
          <el-select v-model="form.paymentMethod">
            <el-option v-for="item in paymentMethodList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('common.placeholderRemark100')" rows="3" maxlength="100" type="textarea"
            show-word-limit="show-word-limit"></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" :label="$t('order.OutboundMethod')" prop="fromType">
          <el-select v-model="form.fromType">
            <el-option v-for="item in fromTypeList" :key="item.id" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <div v-if="!isFinishStatus">
        <div v-if="form.fromType === 1">
          <div class="flex-center mb8">
            <div class="flex-one large-tip bolder-font">
              <el-row class="mb8 mt10" :gutter="10">
                <el-col :span="1.5">
                  <div class="flex-one large-tip bolder-font">{{ $t('common.MaterialDetails') }}</div>
                </el-col>
                <!-- <el-col :span="1.5">
                  <el-button size="small" type="success" plain="plain" icon="el-icon-delete-location"
                    @click="onBatchSetInventory">
                    批量设置仓库/库区
                  </el-button>
                </el-col> -->
              </el-row>
            </div>
            <div class="ops">
              <el-button type="primary" plain="plain" size="small" @click="showAddItem">{{ $t('common.addSKU') }}</el-button>
            </div>
          </div>
          <div class="table">
            <WmsTable :data="form.details" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column :label="$t('common.MaterialName')" align="center" prop="prod.itemName"></el-table-column>
              <el-table-column :label="$t('common.MaterialNo')" align="center" prop="prod.itemNo"></el-table-column>
              <el-table-column :label="$t('common.MaterialType')" align="center" prop="prod.itemType"></el-table-column>
              <el-table-column :label="$t('common.inventory')" align="center" prop="prod.stock"></el-table-column>
              <el-table-column :label="$t('common.planNumber')" align="center" prop="planQuantity" width="150">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.planQuantity" :placeholder="$t('common.planNumber')" size="mini" :min="1"
                    :max="2147483647"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.Warehouse/storage area')" align="center">
                <template slot-scope="scope">
                  {{ scope.row.prod.warehouseName }}/{{ scope.row.prod.areaName }}
                  <!-- <WmsWarehouseCascader v-model="scope.row.place" size="small"></WmsWarehouseCascader> -->
                </template>
              </el-table-column>
              <el-table-column :label="$t('fiance.amount')" align="center" width="150">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.money" :precision="2" @change="selectMoney" size="mini" :min="0"
                    :label="$t('common.pleaseInput')"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.operation')" align="center">
                <template slot-scope="scope">
                  <a class="red" @click="form.details.splice(scope.$index, 1)">{{ $t('common.del') }}</a>
                </template>
              </el-table-column>
            </WmsTable>
            <!-- <el-empty v-if="!form.details || form.details.length === 0" :image-size="48"></el-empty> -->
          </div>
        </div>
        <div v-else>
          <div class="flex-center mb8">
            <div class="flex-one large-tip bolder-font">
              <el-row class="mb8 mt10" :gutter="10">
                <el-col :span="1.5">
                  <div class="flex-one large-tip bolder-font">{{ $t('common.BoxDetails') }}</div>
                </el-col>
              </el-row>
            </div>
            <div class="ops" style="display: inline-flex">
              <el-input v-model="boxCode" prefix-icon="el-icon-search" :placeholder="$t('common.pleaseBOXCODEType')" style="margin-right: 10px"
                @change="searchBoxCode" />
              <el-button type="primary" plain="plain" size="small" @click="showAddBox">{{ $t('common.addBOX') }}</el-button>
            </div>
          </div>
          <div class="table">
            <BoxListComponent ref="boxList" :value="form.details"
              :styleBox="'height: calc(100vh - 210px);overflow: auto;'" />
          </div>
        </div>
      </div>
      <div class="tc mt16">
        <!-- <el-button type="primary" plain="plain" size="small" @click="showAddItem">{{ $t('common.addSKU') }}</el-button> -->
      </div>
      <div class="tc mt16">
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
        <el-button @click="submitForm" type="primary">{{ $t('common.save') }}</el-button>
      </div>
    </div>
    <el-dialog :visible="modalObj.show" :title="modalObj.title" :width="modalObj.width" @close="modalObj.cancel">
      <template v-if="modalObj.component === 'add-item'">
        <item-select ref="item-select" :data="this.form.details" :warehouse-id="this.form.warehouseId" :tenant-id="this.form.customerId"></item-select>
      </template>
      <span slot="footer">
        <el-button v-if="modalObj.cancel" @click="modalObj.cancel">{{ $t('common.cancel') }}</el-button>
        <el-button v-if="modalObj.ok" type="primary" @click="modalObj.ok">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- <BatchWarehouseDialog
      :visible.sync="batchDialogVisible"
      :form-data.sync="batchForm"
      @confirmed="onBatchDialogFinished"
    ></BatchWarehouseDialog> -->
    <el-dialog :visible="boxModalObj.show" :title="boxModalObj.title" :width="boxModalObj.width"
      @close="boxModalObj.cancel">
      <el-form label-width="80px" :model="boxForm" ref="boxForm">
        <el-form-item :label="$t('instorage.No')" prop="receiptNo">
          <el-input v-model="boxForm.receiptNo" :placeholder="$t('common.pleaseInput')" style="width: 46%;"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.selectCustomer')" prop="customerId">
          <WmsCustomerSelect v-model="boxForm.customerId"></WmsCustomerSelect>
        </el-form-item>
        <el-form-item class="flex_one tr">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">{{ $t('common.search') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
      <BoxListComponent ref="boxList" :checkbox="checkbox" :allList="checkbox" :url="'/wms/omsPurchaseBox/list'"
        :methodType="'post'" :return-data="returnBoxData" :params="boxForm"
        :styleBox="'height: calc(100vh - 210px);overflow: auto;'" @selection-change="handleSelectionBoxChange" />
      <span slot="footer">
        <el-button @click="boxModalObj.cancel">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="boxModalObj.ok">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addOrUpdateWmsShipmentOrder,
  getWmsShipmentOrder,
} from "@/api/wms/shipmentOrder";
import ItemSelect from "@/views/components/ItemSelect";
import BatchWarehouseDialog from "@/views/components/wms/BatchWarehouseDialog/index.vue";
import BoxListComponent from "@/views/components/wms/BoxList/index.vue";
import WmsAreaCascader from "@/components/WmsAreaCascader";
import request from '@/utils/request.js'
import { listWmsRack } from "@/api/wms/rack";

export default {
  name: "WmsShipmentOrder",
  props: {
    checkbox: {
      type: Boolean,
      default: true,
    },
  },
  components: { BatchWarehouseDialog, ItemSelect, BoxListComponent, WmsAreaCascader },
  dicts: ["wms_shipment_type"],
  data() {
    return {
      ids: [],
      // 非多个禁用
      multiple: true,
      // 批量设置仓库/库区
      batchDialogVisible: false,
      batchForm: {
        place: [],
      },
      // 表单参数
      form: {
        details: [],
        fromType: 1,
      },
      // 箱子搜索参数
      boxForm: {
        warehouseId: null,
        // areaId: null,
        pageSize: 100000,
      },
      // 表单校验
      rules: {
        customerId: [
          // { required: true, trigger: "blur", message: "请选择客户" },
        ],
      },
      modalObj: {
        show: false,
        title: "",
        width: "50%",
        component: null,
        model: {},
        ok: () => { },
        cancel: () => { },
      },
      boxModalObj: {
        show: false,
        title: "",
        width: "50%",
        component: null,
        model: {},
        ok: () => { },
        cancel: () => { },
      },
      hasSupplier: false,
      // 出入库方式 sku/箱子
      fromTypeList: [
        { label: "SKU", value: 1 },
        { label: this.$t('common.box'), value: 2 },
      ],
      chooseList: [],
      // 扫码枪查箱号
      boxCode: null,
      paymentMethodList: [
        { value: "DOMESTIC", label: this.$t('order.internaloan') },
        { value: "OVERSEAS", label: this.$t('order.overseasCollection') },
      ],
      ContainerOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10000,
        rackNo: null,
        rackName: null,
        areaId: null,
        warehouseId: null,
      },
    };
  },
  watch: {
    "form.customerId": {
      immediate: true,
      handler(value) {
        if (value) {
          this.hasCustomer = true;
        } else {
          this.hasCustomer = false;
        }
      },
    },
  },
  computed: {
    isEdit() {
      const bool = this.$route.query.isEdit;
      return bool
    },
    isFinishStatus() {
      const bool = this.$route.query.isFinish;
      return bool
    },
    YT_roles() {
      // 暂时判断roles为common不是客户的未YT
      if(this.$store.state.user.roles[0] !== 'common') {
        return true
      }
    }
  },
  created() {
    const { id } = this.$route.query;
    if (id) {
      this.loadDetail(id);
    } else {
      this.reset();
    }
  },
  methods: {
    // 获取容器
    getContainerId() {
      const { pageNum, pageSize } = this.queryParams;
      const query = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined,
      };
      const pageReq = { page: pageNum - 1, size: pageSize };
      listWmsRack(query, pageReq).then((response) => {
        const { content } = response;
        this.ContainerOptions = content;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 批量设置仓库/库区 */
    onBatchSetInventory() {
      const { details } = this.form;
      if (!details || details.length === 0) {
        this.$modal.msgError(this.$t('common.pleaseAddSKU'));
        return;
      }
      // 未选中
      if (!this.ids.length) {
        this.$modal.msgError(this.$t('common.pleaseSelectSKU'));
        return;
      }
      this.batchDialogVisible = true;
    },
    onBatchDialogFinished() {
      this.batchDialogVisible = false;
      const [warehouseId, areaId, rackId] = this.batchForm.place || [];
      this.form.details.forEach((it) => {
        // 仅更新已选中
        if (this.ids.includes(it.id)) {
          it.place = [warehouseId, areaId, rackId].filter(Boolean);
        }
      });
    },
    /** 统计出库单金额 */
    selectMoney() {
      let sum = 0;
      this.form.details.map((item) => {
        if (!isNaN(parseFloat(item.money))) {
          sum += item.money;
        }
        return item.money;
      });
      this.form.receivableAmount = sum;
    },
    cancel() {
      this.$router.go(-1)
      // this.$tab.closeOpenPage({ path: "/wms/shipmentOrder" });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        let details = [];
        if (this.form.fromType === 2) {
          details = this.chooseList.map((it) => {
            if (it.place) {
              it.warehouseId = it.place[0];
              it.areaId = it.place[1];
              it.rackId = it.place[2];
            } else {
              it.warehouseId = null;
              it.areaId = null;
              it.rackId = null;
            }
            return {
              boxId: it.id,
              rackId: it.rackId,
              areaId: this.form.warehouseId ? this.form.warehouseId[1] : it.areaId,
              money: it.money,
              warehouseId: this.form.warehouseId ? this.form.warehouseId[0] : it.warehouseId,
              planQuantity: it.planQuantity,
              realQuantity: it.realQuantity,
              shipmentOrderStatus: it.shipmentOrderStatus || 11,
              delFlag: 0,
            };
          });
        } else {
          details = this.form.details.map((it) => {
            if (it.place) {
              it.prod.warehouseId = it.place[0];
              it.prod.areaId = it.place[1];
              it.prod.rackId = it.place[2];
            } else {
              it.prod.warehouseId = null;
              it.prod.areaId = null;
              it.prod.rackId = null;
            }
            return {
              itemId: it.prod.id,
              rackId: it.prod.rackId,
              areaId: it.prod.areaId,
              money: it.money,
              warehouseId: it.prod.warehouseId,
              planQuantity: it.planQuantity,
              realQuantity: it.realQuantity,
              shipmentOrderStatus: it.shipmentOrderStatus,
              delFlag: 0,
            };
          });
        }
        const wareIds = this.form.warehouseId || []
        let req = { ...this.form, warehouseId: wareIds[0] || '', areaId: wareIds[1] || '', details };
        this.form.fromType === 2 ? req.outType = 'BOX' : req.outType = 'SKU'
        // console.log('req', req)
        // return
        addOrUpdateWmsShipmentOrder(req).then((response) => {
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
          this.cancel();
        });
      });
    },
    loadDetail(id) {
      getWmsShipmentOrder(id).then((response) => {
        const { details, items } = response;
        let fromType = items && items.length === 0 ? 2 : 1
        const map = {};
        (items || []).forEach((it) => {
          map[it.id] = it;
        });
        details && details.forEach((it) => (it.prod = map[it.itemId]));
        this.form = {
          ...response,
          fromType: fromType,
          details,
        };
        this.chooseList = details
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shipmentOrderType: 11,
        customerId: null,
        orderNo: null,
        shipmentOrderStatus: 11,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        details: [],
      };
      this.resetForm("form");
    },
    confirmSelectItem() {
      const value = this.$refs["item-select"].getRightList();
      this.form.details = value.map((it) => {
        return {
          id: it.id,
          prod: it,
          planQuantity: null,
          realQuantity: null,
          place: [],
          shipmentOrderStatus: 11,
          delFlag: 0,
        };
      });
      this.closeModal();
    },
    closeModal() {
      this.modalObj.show = false;
    },
    showAddItem() {
      // if (!this.form.warehouseId) {
      //   this.$message.warning('请先选择仓库！')
      // } else {
        try {
          this.$refs["item-select"].initDetailsList(this.form.details);
        } catch (err) { }
        const ok = () => this.confirmSelectItem();
        const cancel = () => this.closeModal();
        this.modalObj = {
          show: true,
          title: this.$t('common.addSKU'),
          width: "50%",
          component: "add-item",
          model: {},
          ok,
          cancel,
        };
      // }
    },
    showAddBox() {
      try {
        this.$refs["item-select"].initDetailsList(this.form.details);
      } catch (err) { }
      const ok = () => this.confirmSelectBox();
      const cancel = () => this.closeBoxModal();
      this.boxModalObj = {
        show: true,
        title: this.$t('common.addBOX'),

        width: "50%",
        component: "add-item",
        model: {},
        ok,
        cancel,
      };
      this.form.warehouseId ? this.boxForm.warehouseId = this.form.warehouseId[0] : this.boxForm.warehouseId = null
      this.getBoxList();
    },
    closeBoxModal() {
      this.boxModalObj.show = false;
    },
    getBoxList() {
      this.$nextTick(() => {
        this.$refs.boxList.getList();
      });
    },
    returnBoxData(data) {
      if (data.content) {
        return data.content;
      }
    },
    handleSelectionBoxChange(v) {
      let c = 0;
      // if(this.chooseList.length > 0 && v.length > 0) {
      //   this.chooseList = [...this.chooseList, ...v]
      // }
      // if(this.chooseList.length === 0) {
      //   this.chooseList = v;
      // }
      this.chooseList = v
      // v.map((r) => {
      //   let v = NP.times(r.boxHigh, r.boxStrong, r.boxWide);
      //   c = NP.plus(c, v);
      //   return r;
      // });
    },
    confirmSelectBox() {
      // 使用filter方法筛选出不同的记录
      const differentRecords = this.chooseList.filter(obj2 => !this.form.details.some(obj1 => obj1.id === obj2.id));
      // 使用some方法检查是否存在相同id的记录
      const hasSameId = this.chooseList.some(obj2 => this.form.details.some(obj1 => obj1.id === obj2.id));
      // 如果存在相同id的记录，则给出提示
      if (hasSameId) {
        console.log("存在相同id");
      }
      // 将不同的记录推送到array1中
      this.form.details.push(...differentRecords);
      this.closeBoxModal();
    },
    searchBoxCode() {
      if (this.boxCode) {
        this.getSearchBoxCodeInfo()
      }
    },
    returnBoxData(data) {
      if (data.content) {
        return data.content;
      }
    },
    getSearchBoxCodeInfo() {
      const data = {
        boxCode: this.boxCode
      }
      request.post('/wms/omsPurchaseBox/list', data).then(r => {
        var res = r
        let list = []
        if (typeof this.returnBoxData === 'function') {
          list = this.returnBoxData(res)
        } else {
          list = res.data
        }
        if (list.length === 0) {
          this.$message.error(this.$t('common.noSearshBoxCodeMsg'))
        } else {
          const found = this.form.details.length > 0 ? this.form.details.find(item => item.id === list[0].id) : null;
          if (found) {
            this.$message.warning(this.$t('common.changeBoxCodeMsg'))
          } else {
            this.form.details.push(list[0]);
          }
        }
        this.boxCode = null
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs.boxList.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.boxForm = {
        pageSize: 100000
      }
      this.handleQuery()
    },
  },
};
</script>
<style lang="stylus">
.shipment-order-edit-wrapper {
  .shipment-order-content {
    width: 70%;
    min-width: 900px;
    margin: 0 auto;
  }
}
</style>
